package com.fy.proj5_permission_transaction_cache.controller;

import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 缓存管理控制器
 */
@RestController
@RequestMapping("/api/cache")
public class CacheController {

    @Autowired
    private CacheService cacheService;

    /**
     * 设置缓存
     */
    @PostMapping
    public ResponseEntity<?> setCache(@RequestBody Map<String, Object> request) {
        try {
            String key = (String) request.get("key");
            Object value = request.get("value");
            Long expireTime = request.containsKey("expireTime") ? Long.valueOf(request.get("expireTime").toString()) : null;
            
            if (key == null || value == null) {
                return ResponseEntity.ok(ResponseUtil.error(400, "key和value不能为空"));
            }
            
            boolean result;
            if (expireTime != null && expireTime > 0) {
                result = cacheService.set(key, value, expireTime);
            } else {
                result = cacheService.set(key, value);
            }
            
            if (result) {
                return ResponseEntity.ok(ResponseUtil.success("缓存设置成功"));
            }
            return ResponseEntity.ok(ResponseUtil.error(500, "缓存设置失败"));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "设置缓存失败: " + e.getMessage()));
        }
    }

    /**
     * 获取缓存
     */
    @GetMapping("/{key}")
    public ResponseEntity<?> getCache(@PathVariable String key) {
        try {
            Object value = cacheService.get(key);
            if (value != null) {
                return ResponseEntity.ok(ResponseUtil.success(value));
            }
            return ResponseEntity.ok(ResponseUtil.error(404, "缓存不存在"));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "获取缓存失败: " + e.getMessage()));
        }
    }

    /**
     * 删除缓存
     */
    @DeleteMapping("/{key}")
    public ResponseEntity<?> deleteCache(@PathVariable String key) {
        try {
            boolean result = cacheService.delete(key);
            if (result) {
                return ResponseEntity.ok(ResponseUtil.success("缓存删除成功"));
            }
            return ResponseEntity.ok(ResponseUtil.error(404, "缓存不存在"));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "删除缓存失败: " + e.getMessage()));
        }
    }

    /**
     * 清除所有缓存
     */
    @DeleteMapping
    public ResponseEntity<?> clearCache() {
        try {
            cacheService.clear();
            return ResponseEntity.ok(ResponseUtil.success("缓存清除成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "清除缓存失败: " + e.getMessage()));
        }
    }

    /**
     * 获取缓存键的过期时间
     */
    @GetMapping("/{key}/expire")
    public ResponseEntity<?> getExpireTime(@PathVariable String key) {
        try {
            Long expireTime = cacheService.getExpire(key);
            Map<String, Long> result = new java.util.HashMap<>();
            result.put("expireTime", expireTime);
            return ResponseEntity.ok(ResponseUtil.success(result));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "获取过期时间失败: " + e.getMessage()));
        }
    }

    /**
     * 设置缓存键的过期时间
     */
    @PutMapping("/{key}/expire")
    public ResponseEntity<?> setExpireTime(@PathVariable String key, @RequestParam Long expireTime) {
        try {
            boolean result = cacheService.expire(key, expireTime);
            if (result) {
                return ResponseEntity.ok(ResponseUtil.success("过期时间设置成功"));
            }
            return ResponseEntity.ok(ResponseUtil.error(404, "缓存不存在或设置失败"));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "设置过期时间失败: " + e.getMessage()));
        }
    }

    /**
     * 检查缓存键是否存在
     */
    @GetMapping("/{key}/exists")
    public ResponseEntity<?> exists(@PathVariable String key) {
        try {
            boolean exists = cacheService.exists(key);
            Map<String, Boolean> result = new java.util.HashMap<>();
            result.put("exists", exists);
            return ResponseEntity.ok(ResponseUtil.success(result));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "检查缓存失败: " + e.getMessage()));
        }
    }

    /**
     * 清除指定前缀的缓存
     */
    @DeleteMapping("/prefix/{prefix}")
    public ResponseEntity<?> clearByPrefix(@PathVariable String prefix) {
        try {
            int count = cacheService.clearByPrefix(prefix);
            Map<String, Integer> result = new java.util.HashMap<>();
            result.put("deletedCount", count);
            return ResponseEntity.ok(ResponseUtil.success(result));
        } catch (Exception e) {
            return ResponseEntity.ok(ResponseUtil.error(500, "清除缓存失败: " + e.getMessage()));
        }
    }
}